package com.huluobo.a2206koltindouyin.home

import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.huluobo.a2206koltindouyin.adapter.CommonPagerAdapter
import com.huluobo.a2206koltindouyin.databinding.FragmentHomeBinding
import com.huluobo.base.bean.NewsTypeBean
import com.huluobo.base.mvvm.BaseFragment
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    private val tabEntities = arrayListOf<CustomTabEntity>()
    private val tabs = mutableListOf<NewsTypeBean>()
    private lateinit var commonPagerAdapter: CommonPagerAdapter
    private val fragments = mutableListOf<Fragment>()
    override fun initData() {
        vm.getNewsType()
        vm.getNewsTypeSuccess.observe(this) { list ->
            tabs.clear()
            tabs.addAll(list)
            tabEntities.clear()
            list.forEach {
                val tabEntity = TabEntity(it.typename, 0, 0, it.id)
                tabEntities.add(tabEntity)
                fragments.add(CommonFragment(it.id))
            }
            binding.homeTab.setTabData(tabEntities)

        }
    }

    override fun initView() {
        binding.homeTab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                binding.homeVp2.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }
        })

        commonPagerAdapter = CommonPagerAdapter(requireActivity(), fragments)
        binding.homeVp2.adapter = commonPagerAdapter

        binding.homeVp2.registerOnPageChangeCallback(object :OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                binding.homeTab.currentTab = position
            }
        })
    }
}